package com.example.wmuqrreader;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class BuildingActivity extends Activity {

	DatabaseHandler db;
	
	Button 		button_save; 
	Button		button_del;
	
	EditText 	buildingNum;
	EditText 	buildingName;
	int 		buildingId;
	
	Bundle 		extras;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_building);
		
		db = new DatabaseHandler(this);
		
		button_save 	= (Button) findViewById(R.id.btn_save);
		button_del		= (Button) findViewById(R.id.btn_scan);
		
		buildingNum 	= (EditText) findViewById(R.id.edittext_buildingNum);
		buildingName 	= (EditText) findViewById(R.id.editText_buildingName);
		
		extras 			= getIntent().getExtras();
		
        //ID Passed - existing inventory
        if (extras != null && extras.getString("BUILDING") != null )
        {
        	populateFields(extras.getString("BUILDING"));
        	button_del.setText("Delete");
        	
        	//Make sure the user cannot delete the NEW STOCK bldg
        	if(Integer.parseInt(extras.getString("BUILDING")) > 1 )
        	{
        		button_del.setVisibility(View.VISIBLE);
        	}
        }
        
		//Add a function for the SAVE button click
        button_save.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				
				//Make a building object from the user input
				Building newBldg = populateBuilding(0);
				
				if(newBldg._num != "" && newBldg._building != "")
				{	
				
					//If exists, update, else add
					if (extras != null && extras.getString("BUILDING") != null )
					{
						if(db.updateBuilding( populateBuilding( Integer.parseInt(extras.getString("BUILDING")) )) > 0)
						{
							Toast.makeText(getApplicationContext(), "Changes saved successfully", Toast.LENGTH_LONG).show();
							db.close();
							
							setResult(RESULT_OK, null);
							finish();
						}
						else
							buildingName.setError("A building with the name " + newBldg._building + " already exists in the database");
					}
					else
					{
											
							//Add the building to the db
							if(db.addBuilding(newBldg) > 0)
							{
								Toast.makeText(getApplicationContext(), "New building added to the database", Toast.LENGTH_LONG).show();
								db.close();
								
								setResult(RESULT_OK, null);
								finish();
							}
							else
								buildingName.setError("A building with the name " + newBldg._building + " already exists in the database");
					}
				}
				else
				{
					if((newBldg._num == "")){ buildingNum.setError("A building number greater than 0 is required"); }
					
					if(newBldg._building == ""){ buildingName.setError("A building name cannot be left blank"); }
				}
			}
        });
        
        //Add a function for the DELETE button click
        button_del.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {	
				ConfirmBldgDelete();
			}
        	
        });
	}
	
	//Populate the BuildingActivity fields from a given building
	private void populateFields(String building_id) {
		
		Building entry = db.getBuilding( Integer.parseInt(building_id) );		
		    	
    	buildingId = entry.get_id();
    	buildingNum.setText( entry.get_num() ); 
		buildingName.setText( entry.get_building() );
		
	}
	
	//Populate a new inventory object from field data
	private Building populateBuilding(int id)
	{		
		String bldgNum = "";
		String bldgName = "";
		
		String tempNum 	= buildingNum.getText().toString();
		String tempName = buildingName.getText().toString();
		
		//Validations
		if(tempNum.length() < 1)
		{
			buildingNum.setError( "A valid building number is required" ); 
		}
		else
			bldgNum = buildingNum.getText().toString();
		
		if(tempName.length() < 1)
		{
			buildingName.setError("A valid building name is required");
		}
		else				
			bldgName = tempName;
		
		if(id > 0) { return new Building(id, bldgNum, bldgName);	}
		else { return new Building(bldgNum, bldgName);	}
	}

	//Ensure the user wants to delete the building before continuing
	private void ConfirmBldgDelete()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Delete Building " + buildingName.getText().toString())
        .setMessage("Deleting a building cannot be undone! All inventory assigned to this building will be moved to NEW STOCK. "
        		+ "Are you sure you wish to proceed? ")
        .setNegativeButton("No", null)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	        	
	        	db.deleteBuilding( populateBuilding( Integer.parseInt(extras.getString("BUILDING")) ) );
	    		Toast.makeText(getApplicationContext(), "Building deleted successfully", Toast.LENGTH_LONG).show();
	    		db.close();
	    		
	    		setResult(RESULT_OK, null);
	    		finish();   
	        }
	    })
	    .show();
	}
}
